<template>
  <div class="production-plan">
    <!-- 头部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">保存</el-button>
      <el-button @click="handleEdit">编辑</el-button>
      <el-button type="success" @click="handleAudit">审核</el-button>
      <el-button type="danger" @click="handleAntiAudit">反审核</el-button>
      <el-button @click="handlePrint">打印</el-button>
      <el-button type="primary" @click="get">返回列表</el-button>
      <el-button @click="handleCollapse">收起</el-button>
    </div>

    <!-- 基本信息区域 -->
    <div class="production-plan-form">
      <el-form :model="formData" :label-width="120">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据编码">
              <el-input v-model="formData.documentCode" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务类型">
              <el-select v-model="formData.businessType" disabled>
                <el-option label="生产计划" value="productionPlan"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-input v-model="formData.salesperson" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单BOM">
              <el-button
                type="text"
                @click="openProductSelector(materialList.materialCode)"
                >查看</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据日期">
              <el-date-picker
                v-model="formData.documentDate"
                type="date"
                style="width: 255px"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                disabled
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作员">
              <el-input v-model="formData.operator" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务单号">
              <el-input v-model="formData.businessOrderNo" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="版本号">
              <el-input v-model="formData.versionNumber" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据状态">
              <el-select v-model="formData.documentStatus">
                <el-option label="开立" value="开立"></el-option>
                <el-option label="审核" value="审核"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核员">
              <el-input v-model="formData.auditor" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单交期">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                placeholder="选择日期"
                style="width: 255px"
                disabled
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="版本说明">
              <el-input v-model="formData.versionDescription"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="业务状态">
              <el-select v-model="formData.businessStatus" disabled>
                <el-option label="正常" value="normal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核日期">
              <el-date-picker
                v-model="formData.auditDate"
                type="date"
                placeholder="选择日期"
                style="width: 255px"
                disabled
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产总量">
              <el-input v-model="formData.productionTotal" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 订单信息表格 -->
    <div class="order-info">
      <h3>订单信息</h3>
      <br />
      <el-table :data="dialogProductList" border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码"></el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column prop="mainUnit" label="主计量"></el-table-column>
        <el-table-column prop="demandquantity" label="数量"></el-table-column>
        <el-table-column
          prop="qualityRequirement"
          label="质量要求"
        ></el-table-column>
        <el-table-column
          prop="packagingRequirement"
          label="包装要求"
        ></el-table-column>
        <el-table-column
          prop="procurementInstructions"
          label="备注"
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" link @click="deleteProduct(scope.row)"
              >删除</el-button
            >
            <el-button
              type="text"
              @click="getMaterialList(scope.row.materialCode)"
              >获取物料清单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 物料清单表格 -->
    <div class="material-list">
      <h3>物料清单</h3>
      <br />
      <el-table :data="materialListData" border>
        <el-table-column
          type="index"
          width="60px"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="billCode"
          width="150px"
          label="单据编码"
        ></el-table-column>
        <el-table-column
          prop="businessStatus"
          label="单据状态"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="businessType"
          label="业务类型"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="billStatus"
          label="状态"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="materialCode"
          label="物料编码"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="materialName"
          label="物料名称"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="mainUnit"
          label="主计量"
          width="110px"
        ></el-table-column>
        <el-table-column prop="supplymode" label="供应方式" width="150px">
          <template #default="scope">
            <el-select
              v-model="scope.row.supplymode"
              placeholder="请选择供应方式"
            >
              <el-option label="委外" value="委外"></el-option>
              <el-option label="加工" value="加工"></el-option>
              <el-option label="生产" value="生产"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="productionQuantity"
          width="110px"
          label="生产数量"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.productionQuantity"
              placeholder="输入数量"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="workshop" label="下发车间" width="150px">
          <template v-slot="scope">
            <el-select v-model="scope.row.workshop" placeholder="请选择车间">
              <el-option label="装配车间" value="装配车间"></el-option>
              <el-option label="加工车间" value="加工车间"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260px">
          <template #default="scope">
            <el-switch v-model="scope.row.status"></el-switch>
            <el-button type="text" @click="bomSupplementary(scope.row)"
              >BOM补料</el-button
            >
            <el-button type="text" @click="productionSupplementary(scope.row)"
              >生产补料</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 补料清单表格 -->
    <div class="supplementary-list">
      <h3>补料清单</h3>
      <br />
      <el-table :data="supplementaryListData" border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="documentCode" label="单据编码"></el-table-column>
        <el-table-column
          prop="documentStatus"
          label="单据状态"
        ></el-table-column>
        <el-table-column prop="businessType" label="业务类型"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码"></el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column prop="mainUnit" label="主计量"></el-table-column>
        <el-table-column prop="supplyMethod" label="供应方式">
          <template #default="scope">
            <el-select
              v-model="scope.row.supplyMethod"
              placeholder="请选择供应方式"
            >
              <el-option label="采购" value="采购"></el-option>
              <el-option label="加工" value="加工"></el-option>
              <el-option label="委外" value="委外"></el-option>
              <el-option label="装配" value="装配"></el-option>
              <el-option label="生产" value="生产"></el-option>
              <el-option label="无" value="无"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="productionQuantity"
          label="生产数量"
          width="150px"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.productionQuantity"
              placeholder="输入数量"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="supplementaryReason"
          label="补料事由"
        ></el-table-column>
        <el-table-column prop="supplementaryDate" label="补料日期">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.supplementaryDate"
              type="date"
              placeholder="选择日期"
              style="width: 255px"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
    </div>
  </div>
  <el-dialog
    title="选择订单"
    ref="dialogRef"
    v-model="dialogVisible"
    width="1200px"
  >
    <div class="search-bar">
      <el-input
        placeholder="请输入分类名称"
        v-model="searchCategory"
        prefix-icon="el-icon-search"
      ></el-input>
      <el-input placeholder="物料编码" v-model="searchCode"></el-input>
      <el-input placeholder="物料名称" v-model="searchName"></el-input>
      <el-button>连选</el-button>
    </div>
    <el-table
      @selection-change="handleSelectionChange"
      :data="materialList"
      border
      style="width: 1800px"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column
        prop="materialCode"
        label="物料编码"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="materialName"
        label="物料名称"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="modelSpec"
        label="型号规格"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="mainUnit"
        label="主计量"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="procurementInstructions"
        label="备注"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="demandquantity"
        label="数量"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="businessPerson"
        label="业务人员"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="billCode"
        label="业务单号"
        width="130"
      ></el-table-column>
      <el-table-column
        v-slot="scoped"
        prop="orderDeliveryDate"
        label="订单交期"
        width="120"
      >
        <!-- {{ scoped.row.creationDate.substring(0, 10) }} -->
        {{ scoped.row.orderDeliveryDate.substring(0, 10) }}
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="form1.PageIndex"
      v-model:page-size="form1.PageSize"
      :page-sizes="[1, 3, 15, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="form1.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <br />
    <div class="button-group">
      <el-button @click="closeDialog" class="action-button">关闭</el-button>
      <el-button type="primary" @click="confirmSelection" class="action-button"
        >选择</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
const handleAudit = () => {
  // 反填死数据：审核员固定为"系统审核员"，审核日期为当前日期
  formData.auditor = "陈平安";
  formData.auditDate = new Date();
  ElMessage.success("审核成功");
};
const get = () => {
  router.push("/GetProduce");
};
// 定义前端数据模型
const formData = reactive({
  documentCode: "",
  businessType: "productionPlan",
  salesperson: "",
  documentDate: dayjs().format("YYYY-MM-DD"), // 匹配后端DateTime
  operator: "陈平安",
  businessOrderNo: "",
  versionNumber: "1.0",
  documentStatus: "",
  auditor: "",
  deliveryDate: null as Date | null,
  versionDescription: "",
  businessStatus: "normal",
  auditDate: null as Date | null,
  remark: "",
  productionTotal: "",
  materialCode: "",
});

// 提前定义 dialogProductList
const dialogProductList = ref<any[]>([]);
const dialogSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  dialogSelection.value = val;
};

const confirmSelection = () => {
  const selectedRows = dialogSelection.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    dialogProductList.value.push({
      materialCode: selectedProduct.materialCode,
      materialName: selectedProduct.materialName,
      modelSpec: selectedProduct.modelSpec,
      mainUnit: selectedProduct.mainUnit,
      demandquantity: selectedProduct.demandquantity, // 假设默认数量为1，可根据实际调整
      procurementInstructions: selectedProduct.procurementInstructions,
      businessPerson: selectedProduct.businessPerson,
      billCode: selectedProduct.billCode, // 假设默认数量为1，可根据实际调整
      orderDeliveryDate: selectedProduct.orderDeliveryDate,
    });
  });
  const totalQuantity = dialogProductList.value.reduce(
    (sum, item) => sum + (item.demandquantity || 0),
    0
  );
  formData.productionTotal = totalQuantity.toString();
  if (selectedRows.length > 0) {
    const firstRow = selectedRows[0]; // 假设取第一个选中行的相关字段，若有特殊逻辑可调整
    formData.salesperson = firstRow.businessPerson; // 业务员
    formData.businessOrderNo = firstRow.billCode; // 业务单号
    formData.deliveryDate = new Date(firstRow.orderDeliveryDate); // 订单交期，转换为Date类型以适配日期选择器
  }
  if (selectedRows.length > 0) {
    formData.materialCode = selectedRows[0].materialCode; // 按实际字段名调整
  }
  closeDialog();
};

const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});

// 分页 - 每页数量变化
const handleSizeChange = (newSize: number, materialCode: string) => {
  form1.PageSize = newSize;
  searchProducts();
};

// 分页 - 当前页变化
const handleCurrentChange = (newPage: number, materialCode: string) => {
  form1.PageIndex = newPage;
  searchProducts();
};

// 对话框可见性
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const closeDialog = () => {
  dialogVisible.value = false;
  dialogSelection.value = []; // 清空已选
};
const closeDialog1 = () => {
  dialogVisible1.value = false;
  dialogSelection.value = []; // 清空已选
};
// 物料列表数据
const materialList = ref<any[]>([]);
const materialListData = ref<any[]>([]); // 物料清单数据
const supplementaryListData = ref<any[]>([]);
// 搜索条件
const searchCategory = ref("");
const searchCode = ref("");
const searchName = ref("");

// 打开物料选择对话框
const openProductSelector = async () => {
  dialogVisible.value = true;

  searchProducts();
};

const searchProducts = () => {
  dialogVisible.value = true;
  axios
    .get("http://localhost:5202/api/Log/GetProcurement", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      materialList.value = res.data.data.list || [];
      form1.TotalCount = res.data.data.totalCount || 0;
      form1.PageCount = res.data.data.PageCount || 0;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
      ElMessage.error("获取物料列表失败，请检查网络或重试");
    });
};

// 删除订单信息表格中的产品
const deleteProduct = (product) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = dialogProductList.value.indexOf(product);
      if (index !== -1) {
        dialogProductList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};
//物料清单反填
const getMaterialList = (materialCode: string) => {
  axios
    .get(
      `http://localhost:5202/api/Log/EditMaterialsBliiProcurements?materialCode=${materialCode}`
    )
    .then((res) => {
      materialListData.value = res.data.data || []; // 填充物料清单表格数据
    })
    .catch((error) => {
      console.error("获取物料清单失败", error);
      ElMessage.error("获取物料清单失败，请检查网络或重试");
    });
};
const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 12; i++) {
    // 生成12位数字
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};
// 定义与后端AddMultiTableDataCommand匹配的请求参数类型
interface ProductionPlanDto {
  DocumentCode: string;
  BusinessType: string;
  Salesperson: string;
  DocumentDate: string;
  Operator: string;
  BusinessOrderNo: string;
  VersionNumber: string;
  DocumentStatus: string;
  Auditor: string;
  DeliveryDate: string | null;
  VersionDescription: string;
  BusinessStatus: string;
  AuditDate: string | null;
  Remark: string;
  ProductionTotal: string;
  materialCode: string;
}

interface ProcurementMateialsDto {
  MaterialCode: string;
  MaterialName: string;
  ModelSpec: string;
  MainUnit: string;
  Demandquantity: number;
  ProcurementNum: number; // 前端需补充该字段（假设来自页面）
  RequiredDate: string; // 前端需补充该字段（假设来自页面）
  ProcurementInstructions: string;
}

interface PlanBillinfoDto {
  MaterialCode: string;
  MaterialName: string;
  ModelSpec: string;
  MainUnit: string;
  Demandquantity: number;
  Materialmethod: string; // 前端需补充该字段（假设来自页面）
  Supplymode: string;
  Workshop: string;
  Status: boolean; // 前端需补充该字段（假设来自页面）
}

interface AddMultiTableDataRequest {
  ProductionPlan: ProductionPlanDto;
  ProcurementMateials: ProcurementMateialsDto[];
  PlanBillinfo: PlanBillinfoDto[];
}
const handleAdd = async () => {
  try {
    // 整理生产计划数据（formData）
    const productionPlanDto: ProductionPlanDto = {
      DocumentCode: formData.documentCode,
      BusinessType: formData.businessType,
      Salesperson: formData.salesperson,
      DocumentDate: formData.documentDate,
      Operator: formData.operator,
      BusinessOrderNo: formData.businessOrderNo,
      VersionNumber: formData.versionNumber,
      DocumentStatus: formData.documentStatus,
      Auditor: formData.auditor,
      DeliveryDate: formData.deliveryDate
        ? dayjs(formData.deliveryDate).format("YYYY-MM-DD")
        : null,
      VersionDescription: formData.versionDescription,
      BusinessStatus: formData.businessStatus,
      AuditDate: formData.auditDate
        ? dayjs(formData.auditDate).format("YYYY-MM-DD")
        : null,
      Remark: formData.remark,
      ProductionTotal: formData.productionTotal,
      materialCode: formData.materialCode,
    };

    // 整理采购物料数据（dialogProductList）
    const procurementMateialsDto: ProcurementMateialsDto[] =
      dialogProductList.value.map((item) => ({
        MaterialCode: item.materialCode,
        MaterialName: item.materialName,
        ModelSpec: item.modelSpec,
        MainUnit: item.mainUnit,
        Demandquantity: Number(item.demandquantity),
        // 以下字段需根据前端页面补充（示例值，需替换为实际业务逻辑）
        ProcurementNum: Number(item.demandquantity), // 假设采购数量=需求数量
        RequiredDate: dayjs().format("YYYY-MM-DD"), // 假设需求日期为今日（需根据页面实际字段调整）
        ProcurementInstructions: item.procurementInstructions,
      }));

    // 整理计划单据数据（materialListData）
    const planBillinfoDto: PlanBillinfoDto[] = materialListData.value.map(
      (item) => ({
        MaterialCode: item.materialCode,
        MaterialName: item.materialName,
        ModelSpec: item.modelSpec,
        MainUnit: item.mainUnit,
        Demandquantity: Number(item.productionQuantity), // 假设需求数量=生产数量
        // 以下字段需根据前端页面补充（示例值，需替换为实际业务逻辑）
        Materialmethod: "默认方式", // 需根据页面实际字段调整
        Supplymode: item.supplymode,
        Workshop: item.workshop,
        Status: item.status, // 需根据页面实际字段调整
      })
    );

    // 构造完整请求体
    const requestBody: AddMultiTableDataRequest = {
      ProductionPlan: productionPlanDto,
      ProcurementMateials: procurementMateialsDto,
      PlanBillinfo: planBillinfoDto,
    };
    console.log(requestBody);
    // 调用后端API（假设后端接口地址为 /api/AddMultiTableData）
    const response = await axios.post(
      "http://localhost:5027/api/Log/AddMultiTableData",
      requestBody
    );

    if (response.data.code === 200) {
      ElMessage.success("保存成功");
      router.push("/GetProduce");
    } else {
      ElMessage.error(`保存失败：${response.data.message}`);
    }
  } catch (error) {
    ElMessage.error("保存失败：网络请求异常");
    console.error("保存请求异常", error);
  }
};
onMounted(() => {
  formData.documentCode = generateTwelveDigitNumber();
});
</script>

<style scoped>
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}
.production-plan {
  padding: 10px;
}
.operation-bar {
  margin-bottom: 10px;
  text-align: right;
}
.basic-info {
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  padding: 10px;
}
.order-info,
.material-list,
.supplementary-list {
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  padding: 10px;
}
.el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
}
.el-form-item {
  width: 100%;
  text-align: left;
}
.el-form-item__label {
  text-align: left;
}
/* 表格内容垂直居中 */
.el-table__body tr td {
  vertical-align: middle;
}
/* 对话框内表格头部样式优化 */
.el-table__header th {
  background-color: #f5f7fa;
  color: #606266;
}
</style>